import Alamofire
import SwiftUI
import CommonCrypto


let baseUrl = "https://www.haowangpt.cn:9443/"
//let baseUrl = "https://localhost:9443/"


class SignRequestInterceptor: RequestInterceptor {
    var version: String
    var key: String
    init(version: String, key: String) {
        self.version = version
        
        self.key = key
    }
    
    func adapt(_ urlRequest: URLRequest, using state: RequestAdapterState, completion: @escaping (Result<URLRequest, Error>) -> Void) {
        var request = urlRequest
        
        let timeInterval: String = "\(Date().milliStamp)"
        
        let sign = "\(version)\(StoreManager.getBid())\(timeInterval)5b3a5158289a85d03da1d13163e0060d\(key)".utf8EncodedString().sha256()
        print("timeInterval==\(timeInterval) sign=\(sign)")
        if request.method == .post{
            var content: String = ""
            if request.httpBody != nil{
                if let bodyContent = String(data: request.httpBody!, encoding: .utf8){
                    content = bodyContent
                }
            }
        
            if !content.contains("bid"){
                content += "&bid=\(StoreManager.getBid())"
            }
            
            if !content.contains("vip"){
                content += "&vip=\(StoreManager.isVip())"
            }
            
            if !content.contains("uid"){
                content += "&uid=\(StoreManager.getUid())"
            }
            
            if !content.contains("uuid"){
                content += "&uuid=\(StoreManager.getUUIDString())"
            }
            
            if !content.contains("version"){
                content += "&version=\(StoreManager.getVersion())"
            }
            content += "&timeInterval=\(timeInterval)"
            content += "&sign_key=\(key)"
            content += "&sign=\(sign)"
            if content.starts(with: "&"){
                if let range = content.range(of:"&") {
                    content = content.replacingCharacters(in: range, with:"")
                }
            }
           
            print("content======\(content)")
            
            request.httpBody = content.data(using: .utf8)
        }else{
            
            if let absoluteString = request.url?.absoluteString{
                var urlComponents = URLComponents(string: absoluteString)
                
                urlComponents?.queryItems?.append(URLQueryItem(name: "vip", value: "\(StoreManager.isVip())"))
                urlComponents?.queryItems?.append(URLQueryItem(name: "bid", value: StoreManager.getBid()))
                urlComponents?.queryItems?.append(URLQueryItem(name: "uid", value: "\(StoreManager.getUid())"))
                urlComponents?.queryItems?.append(URLQueryItem(name: "uuid", value: "\(StoreManager.getUUIDString())"))
                urlComponents?.queryItems?.append(URLQueryItem(name: "version", value: StoreManager.getVersion()))
                urlComponents?.queryItems?.append(URLQueryItem(name: "sign_key", value: key))
                urlComponents?.queryItems?.append(URLQueryItem(name: "timeInterval", value: timeInterval))
                urlComponents?.queryItems?.append(URLQueryItem(name: "sign", value: sign))
                request.url = urlComponents?.url
            }
            
        }
        
        completion(.success(request))
    }
    func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void) {
        
        completion(.success(urlRequest))
    }
    
    func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) {
        completion(.retry)
    }
    
}




class AFManager {
    static let sharedInstance = AFManager()
    var manager:Session
    private init(){
        
                let trustManager = ServerTrustManager(evaluators: ["www.haowangpt.cn": DisabledTrustEvaluator()])
//        let trustManager = ServerTrustManager(evaluators: ["localhost": DisabledTrustEvaluator()])
        let configuration = URLSessionConfiguration.af.default
        
        let characters: String = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM"
        var ranStr = ""
        for _ in 0..<30 {
            let index = Int(arc4random_uniform(UInt32(characters.count)))
            let start = characters.index(characters.startIndex, offsetBy: index)
            let end = characters.index(characters.startIndex, offsetBy: index)
            ranStr.append(contentsOf: characters[start...end])
        }
        let key = ranStr
        
        let version = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
        let bid = StoreManager.getBid()
        UserDefaults.standard.set(version, forKey: key_version)
        UserDefaults.standard.set(bid, forKey: key_bid)
 
        configuration.timeoutIntervalForRequest = 120//120s超时时间
            
        
        
        
        manager = Session(configuration: configuration, interceptor:SignRequestInterceptor(version: version,key:key), serverTrustManager: trustManager)
        
    }
    func getRandom() -> String{
        let characters: String = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM"
        var ranStr = ""
        for _ in 0..<30 {
            let index = Int(arc4random_uniform(UInt32(characters.count)))
            let start = characters.index(characters.startIndex, offsetBy: index)
            let end = characters.index(characters.startIndex, offsetBy: index)
            ranStr.append(contentsOf: characters[start...end])
        }
        return ranStr
    }
    
}



extension String {
    func sha256() -> String{
        if let stringData = self.data(using: String.Encoding.utf8) {
            return hexStringFromData(input: digest(input: stringData as NSData))
        }
        return ""
    }
    
    private func digest(input : NSData) -> NSData {
        let digestLength = Int(CC_SHA256_DIGEST_LENGTH)
        var hash = [UInt8](repeating: 0, count: digestLength)
        CC_SHA256(input.bytes, UInt32(input.length), &hash)
        return NSData(bytes: hash, length: digestLength)
    }
    
    private  func hexStringFromData(input: NSData) -> String {
        var bytes = [UInt8](repeating: 0, count: input.length)
        input.getBytes(&bytes, length: input.length)
        
        var hexString = ""
        for byte in bytes {
            hexString += String(format:"%02x", UInt8(byte))
        }
        
        return hexString
    }
    
    func utf8EncodedString()-> String {
        let messageData = self.data(using: .nonLossyASCII)
        let text = String(data: messageData!, encoding: .utf8) ?? ""
        return text
    }
}
extension Date {
    
    /// 获取当前 秒级 时间戳 - 10位
    var timeStamp : String {
        let timeInterval: TimeInterval = self.timeIntervalSince1970
        let timeStamp = Int(timeInterval)
        return "\(timeStamp)"
    }
    
    /// 获取当前 毫秒级 时间戳 - 13位
    var milliStamp : String {
        let timeInterval: TimeInterval = self.timeIntervalSince1970
        let millisecond = CLongLong(round(timeInterval*1000))
        return "\(millisecond)"
    }
}
